/* 
 * @Author: panqian
 * @Date:   2017-06-20 13:38:28
 * @Last Modified by:   panqian
 * @Last Modified time: 2017-06-23 14:35:54
 */

/*
 左侧功能按钮
 * */

namespace('n2.billboard');

n2.billboard = function() {
	this._viwer = null;
	this._camera = null;
	this._handler = null;
	this._scene = null;
	n2.base(this, n2.main);
};

n2.definePrototype(n2.billboard.prototype, {
	viewer: {
		get: function() {
			return this._viewer;
		},
		set: function(value) {
			this._viewer = value;
		}
	},
	handler: {
		get: function() {
			return this._handler;
		},
		set: function(value) {
			this._handler = value;
		}
	},
	camera: {
		get: function() {
			return this._camera;
		},
		set: function(value) {
			this._camera = value;
		}
	},
	scene: {
		get: function() {
			return this._scene;
		},
		set: function(value) {
			this._scene = value;
		}
	}
});

n2.billboard.prototype.init = function() {
	var self = this;
	var viewer = self.viewer = n2.viewer;
	var scene = viewer.scene;
	var camera = viewer.camera;
	var searchInp = document.querySelector("#searchInp");
	var claerVal = document.querySelector("#claerVal");
	var img_yj = document.querySelector("#img_yj");
	var contentBox = document.getElementById("response");
	var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
	self.primitive = null;
	//画出所有地震点位
	n2.ajax.post('http://' + n2.board, {
		"kind_code": "01",
	}, "json").then(function(res) {
		var res = JSON.parse(res)[1]["data"];
		var len = res.length;
		//搜索功能
		searchInp.oninput = function() {
			var val = this.value;
			if(val.length != 0) {
				claerVal.className = "";
			} else {
				claerVal.className = "disnone";
			}
			disasterSearch(res, val);
		}

		claerVal.addEventListener("tap", function() {
			searchInp.value = "";
			claerVal.className = "disnone";
			disasterSearch();
			searchInp.blur();
		})

		//侧边栏地震信息
		dizhenxinxiList(contentBox, res);

		//"ⅠⅡⅢⅣ"
		//球左下角次数
		var magi = [0, 0, 0, 0];
		for(var i = 0; i < len; i++) {
			var disasterTextMag = parseInt(res[i]['disaster_text']['mag']);
			if(disasterTextMag < 4) {
				continue;
			} else if(4 <= disasterTextMag && disasterTextMag < 5) {
				magi[0]++;
			} else if(5 <= disasterTextMag && disasterTextMag < 6) {
				magi[1]++;
			} else if(6 <= disasterTextMag && disasterTextMag < 7) {
				magi[2]++;
			} else if(7 <= disasterTextMag) {
				magi[3]++;
			};
		};
		//左下角动态写入灾害次数
		img_yj.innerHTML = '<img src="images/tuli.png" class="img-responsive">' +
			'<div id="totalDegree">' +
			'<p><span class="span">' + magi[0] + '</span> 次</p>' +
			'<p><span class="span">' + magi[1] + '</span> 次</p>' +
			'<p><span class="span">' + magi[2] + '</span> 次</p>' +
			'<p><span class="span">' + magi[3] + '</span> 次</p>' +
			'</div>';
		//cesium上显示的小红点
		var scene = viewer.scene;
		var billboards = scene.primitives.add(new Cesium.BillboardCollection());
		for(var p = 0; p < len; p++) {
			if(res[p].disaster_text.mag >= 4) {
				var longitude = res[p].disaster_text.lon;
				var latitude = res[p].disaster_text.lat;
				var height = 0;
				var t = res[p].disaster_text;
				(function(t) {
					//根据地震震级显示不同大小的点
					billboards.add({
						position: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
						image: './images/' + Math.floor(t.mag) + '.png',
						id: res[p].disaster_id,
						width: Math.floor(t.mag) * 3,
						height: Math.floor(t.mag) * 3
					})
				})(t)
			};
		}
	});

	var clickStatus = true; //气泡能否出现的状态，上一个气泡没有生成的时候，不允许下一个气泡发送生成链接
	//左键单击地震点显示地震详细信息
	handler.setInputAction(function(event) {
		var o = viewer.scene.pick(event.position);
		//获取点击的最上方的元素
		if(o === undefined) {
			if(self.primitive != null) {
				scene.primitives.remove(self.primitive)
			}
			return;
		}

		if(typeof(o.id) === 'string') {
			var num = (o.id).indexOf('s');
			if(num === -1) {
				ck(o);
			} else {
				var leng = (o.id).length;
				var newId = (o.id).substr(0, leng - 1);
				//打开详情页面
				mui.openWindow({
					url: 'dizhenzaihaizhuanti.html',
					id: 'dizhenzaihaizhuanti.html',
					createNew: true,
					show: {
						autoShow: true, //页面loaded事件发生后自动显示，默认为true
						aniShow: 'pop-in',
						duration: '100'
					},
					extras: {
						detail_id: newId
					},
					styles: {
//						popGesture: 'close',
						hardwareAccelerated: true
					},
					waiting: {
						autoShow: true
					}
				});
			}
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	//时间查询
	var asidedate = document.querySelector("#asidedate");
	var asval = getNowFormatDate();
	asidedate.onchange = function() {
		asval = asidedate.value + " 00:00:00";
	}
	var filterclick = document.querySelector("#filterclick");
	filterclick.addEventListener("tap", function(e) {
		//还要加节流阀
		n2.ajax.post('http://' + n2.board, {
			"kind_code": "01",
			"startdate": asval
		}, "json").then(function(res) {
			var res = JSON.parse(res)[1]["data"];
			dizhenxinxiList(contentBox, res);
		})
	})

	var ck = function(that) {
		if(self.primitive != null) {
			scene.primitives.remove(self.primitive);
		}
		var ids = that.title || that.id;
		n2.ajax.post('http://' + n2.billId, {
			"kind_code": "01",
			"product_code": "0001",
			"id": ids
		}, 'json').then(function(res) {
			if(clickStatus) {
				clickStatus = false;
			} else {
				if(self.primitive != null) {
					scene.primitives.remove(self.primitive);
				}
				return false;
			}
			res = JSON.parse(res);
			var canvas = document.createElement("canvas");
			canvas.width = 290;
			canvas.height = 310;
			var ctx = canvas.getContext("2d");
			var longitude1 = res.lon;
			var latitude1 = res.lat;
			var height = 0;
			var title = res.name;
			var happenTime = "发震时刻：" + getNowFormatDate(res.disaster_happendate);
			var latText = "纬度：" + latitude1;
			var lonText = "经度：" + longitude1;
			var deepText = "深度：" + res.deep;
			var magText = "震级：" + res.mag;
			var elevationText = "震中海拔：" + res.elevation;
			var image = new Image();
			image.src = './images/billboard8.png';
			var devicePixelRatio = window.devicePixelRatio || 1,
				backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1,
				ratio = devicePixelRatio / backingStoreRatio;
			var oldWidth = 290;
			var oldHeight = 310;
			canvas.width = oldWidth * ratio;
			canvas.height = oldHeight * ratio;
			canvas.style.width = oldWidth + 'px';
			canvas.style.height = oldHeight + 'px';
			ctx.scale(ratio, ratio);
			image.onload = function() {
				ctx.drawImage(image, 0, 0);
				ctx.lineWidth = 1;
				ctx.font = "14px Modern"; //Microsoft YaHei UI
				ctx.fontWeight = "bold";
				ctx.strokeStyle = "#000066";
				if(title.length > 22) {
					var title1 = title.substring(0, 19);
					var title2 = title.substring(19, title.length);
					ctx.strokeText(title1, 18, 20);
					ctx.strokeText(title2, 18, 35);
				} else {
					ctx.strokeText(title, 18, 30);
				}
				ctx.font = "12px Modern"; //Microsoft YaHei UI
				ctx.strokeStyle = "#333";
				ctx.strokeText(happenTime, 20, 50);
				ctx.strokeText(latText, 20, 65);
				ctx.strokeText(lonText, 20, 80);
				ctx.strokeText(deepText, 20, 95);
				ctx.strokeText(magText, 20, 110);
				ctx.strokeText(elevationText, 20, 125);
				var imgBaes64 = canvas.toDataURL("image/png");
				var img = new Image();
				img.src = imgBaes64;
				img.onload = function() {
					self.primitive = scene.primitives.add(new Cesium.BillboardCollection());
					self.primitive.add({
						position: Cesium.Cartesian3.fromDegrees(longitude1, latitude1, 0),
						image: img,
						horizontalOrigin: Cesium.HorizontalOrigin.Center,
						pixelOffset: new Cesium.Cartesian2(1.0, 0),
						pixelOffsetScaleByDistance: new Cesium.NearFarScalar(1.5e2, 3.0, 1.5e7, 0),
						width: 290,
						height: 308,
						id: ids + 's'
					})
					clickStatus = true;
				}
			};
			image.style.width = '290px';
			image.style.height = '308px';
			image.style.backgroundRepeat = "no-repeat";
			image.style.backgroundPosition = "center";

			//获取当前视角的高度
			var height1 = camera.position;
			var height2 = Cesium.Cartographic.fromCartesian(height1).height;
			camera.flyTo({
				destination: Cesium.Cartesian3.fromDegrees(longitude1, latitude1, height2),
				duration: 1
			})
			searchInp.blur();
		})
	}

	//搜索创建展示列表
	function disasterSearch(res, val) {
		var datas = res || [];
		var box = document.querySelector("#headerBox")
		//获取内容并判断
		var val = val || ""; //文本框中的内容
		//从datas里面寻找和val匹配的项目 如果匹配放到一个新数组中
		var filterArr = [];
		for(var i = 0; i < datas.length; i++) {
			var data = datas[i]["disaster_name"];
			if(data.indexOf(val) >= 0) {
				filterArr.push(datas[i]);
			}
		}

		//1.div会重叠
		//在创建div之前 先判断一下有没有 如果有要先把之前的div删除
		var popDiv = document.getElementById("pop");
		//如果有 就是对象 如果没有就是null
		if(popDiv) {
			//如果能进来 说明已经有了 如果有了就要删除
			box.removeChild(popDiv);
		}
		//2.如果没有匹配项 就不创建了
		if(filterArr.length === 0) {
			return;
		}
		//3.如果用户输入为空 也不创建了
		if(val === "") {
			return;
		}
		//动态生成结构
		popDiv = document.createElement("div");
		popDiv.id = "pop";
		box.appendChild(popDiv);
		var ul = document.createElement("ul");
		popDiv.appendChild(ul);
		var FAL = filterArr.length > 10 ? 10 : filterArr.length;
		//根据filterArr里的数据 创建li 并追加到ul中
		for(var i = 0; i < FAL; i++) {
			var title = filterArr[i]["disaster_name"]; //名称
			var time = "发震时刻：" + getNowFormatDate(filterArr[i]["disaster_happendate"]); //时间
			var li = document.createElement("li");
			li.title = filterArr[i].disaster_id;
			var h4 = document.createElement("h4");
			var p = document.createElement("p");
			title = title.length > 22 ? title.substring(0, 20) + "..." : title;
			h4.innerText = title;
			p.innerText = time; //处理一下兼容问题
			li.appendChild(h4);
			li.appendChild(p);
			ul.appendChild(li);
			li.addEventListener('tap', function(event) {
				ck(this);
				searchInp.blur();
				searchInp.value = "";
				claerVal.className = "disnone";
				box.removeChild(popDiv);
			}, false);
		}
	}

	//信息列表
	function dizhenxinxiList(dom, res) {
		dom["innerHTML"] = '';
		//左下角灾害次数计数
		for(var i = 0; i < res.length; i++) {
			var div = document.createElement('li')
			div.className = 'box';
			var span = document.createElement('span');
			span.className = 'mui-icon mui-icon-info mui-pull-right spanClick';
			span.title = res[i].disaster_id;
			div.appendChild(span);
			var h6 = document.createElement('h6');
			h6.title = res[i].disaster_id;
			h6.className = 'lastBtn';
			h6.innerHTML = res[i].disaster_name;
			div.appendChild(h6);
			var p = document.createElement('p');
			p.innerHTML = getNowFormatDate(res[i].disaster_happendate);
			p.style.fontSize = '14px';
			div.appendChild(p);
			dom.appendChild(div);
			h6.addEventListener('tap', function(event) {
				mui('.zuocehua').offCanvas('close');
				ck(this);
			}, false);
			span.addEventListener('tap', function(event) {
				var newId = this.title;
				//打开详情页面
				mui.openWindow({
					url: 'dizhenzaihaizhuanti.html',
					id: 'dizhenzaihaizhuanti.html',
					show: {
						autoShow: true, //页面loaded事件发生后自动显示，默认为true
						aniShow: 'pop-in',
						duration: '100',
					},
					createNew: true,
					extras: {
						detail_id: newId
					},
					styles: {
//						popGesture: 'close',
						hardwareAccelerated: true
					},
					waiting: {
						autoShow: true
					}
				});
			}, false);
		}
	}
}